﻿using GSPatEditor.Pat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GSPatEditor.UI
{
    partial class AnimationPreview : Form
    {
        public static void ShowPreviewWindow(Animation animation, Palette pal)
        {
            var form = new AnimationPreview() { animation = animation, palette = pal };
            form.clock.Start();
            form.InitFrameInfo();
            form.CreateImageList();
            Application.Run(form);
        }

        private Animation animation;
        private Palette palette;
        private Stopwatch clock = new Stopwatch();
        private int[] frameIndex;
        private System.Drawing.Bitmap[] cachedImage;

        public AnimationPreview()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Invalidate();
        }

        private void InitFrameInfo()
        {
            int count = animation.FrameList.Sum(f => f.FrameCount);
            frameIndex = new int[count];
            int currentFrame = 0, currentFrameStart = 0;
            for (int i = 0; i < count; ++i)
            {
                if (currentFrameStart + animation.FrameList[currentFrame].FrameCount == i)
                {
                    currentFrame += 1;
                    currentFrameStart = i;
                }
                frameIndex[i] = currentFrame;
            }
        }

        private void CreateImageList()
        {
            cachedImage = new System.Drawing.Bitmap[animation.FrameList.Count];
            for (int i = 0; i < cachedImage.Length; ++i)
            {
                cachedImage[i] = animation.FrameList[i].Image.Image.CreateBitmapWithPalette(palette);
                var c0 = cachedImage[i].GetPixel(0, 0);
            }
        }

        private int GetCurrentFrame()
        {
            long frameCount = clock.ElapsedMilliseconds / 16;
            return frameIndex[frameCount % frameIndex.Length];
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            int frame = GetCurrentFrame();
            e.Graphics.Clear(Color.White);
            e.Graphics.DrawImage(cachedImage[frame], new Point(0, 0));
        }
    }
}
